package com.odontosis.view.cadastro.usuario;

import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.odontosis.dao.PacienteDAO;
import com.odontosis.dao.UsuarioDAO;
import com.odontosis.entidade.GrupoUsuario;
import com.odontosis.entidade.Usuario;
import com.odontosis.service.UsuarioService;
import com.odontosis.view.OdontosisAction;

public class AcaoInclusaoUsuario  extends OdontosisAction<UsuarioService> {
	
	public Usuario usuario;
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormInclusaoUsuario formulario = (FormInclusaoUsuario) form;
		if(StringUtils.isEmpty(formulario.getMetodo()))
		{
			return onIniciarTela(mapping, form, request, response);
		}
		return onSalvarUsuario(mapping, form, request, response);
	}
	
	
	public ActionForward onIniciarTela(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormInclusaoUsuario formulario = (FormInclusaoUsuario) form;
		if(formulario.getId() != null){
			usuario = new Usuario();
			usuario = service.load(formulario.getId());	
			formulario.transferirParaForm(formulario, usuario);
			formulario.setGrupoUsuario(usuario.getGrupo().getId().toString());
			formulario.setEdicao("true");
		}else{
			formulario.setEdicao(null);
		}
		return mapping.getInputForward();
	}
	
	public ActionForward onSalvarUsuario(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormInclusaoUsuario formulario = (FormInclusaoUsuario) form;
		
		usuario = new Usuario();
		
		if(formulario.getId() != null && formulario.getId().longValue() != 0){
			usuario = service.load(formulario.getId());
		}
		if(usuario == null){
			usuario = new Usuario();
		}
		
		//transfere de formulario para usuario
		formulario.transferirParaBOs(formulario, usuario);
		usuario.setGrupo(GrupoUsuario.recuperarPorId(Integer.parseInt(formulario.getGrupoUsuario())));
		
		if(usuario.getId() != null && usuario.getId().longValue() == 0){
			usuario.setId(null);
		}
		service.saveOrUpdate(usuario);
		
		Collection<String> sucesso = new ArrayList<String>();
		sucesso.add("Registro Atualizado Com Sucesso");
		request.setAttribute("sucesso", sucesso);
		request.setAttribute("mensagens", null);
		
		return mapping.findForward("lista");
	}

	
}
